package uk.org.kano.wifilogin.data;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;

import uk.org.kano.wifilogin.R;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Toast;

/**
 * This is the interface to load and retrieve accesspoint configurations
 * from disk. When instantiated, if the configurations directory is not
 * found, it will initialise it from the default location.
 * @author timh
 *
 */
public class APAdapter extends BaseAdapter
{
	// The context to hold
	private Context context = null;
	
	// The known accesspoints
	private String[] aps = null;
	private WifiConfigDef[] configs = null;
	
	/**
	 * Initialise the APs store
	 */
	public APAdapter(Context context)
	{
		this.context = context;
		init();
	}
	
	/**
	 * initialise the list
	 */
	private void init()
	{
		int i;
		// Open up the configuration directory and scan it
		File cfgdir = context.getDir(context.getString(R.string.apa_cfg_dir), Context.MODE_PRIVATE);
		
		aps = cfgdir.list();
		if (null == aps) {
			aps = new String[0];
		}
		
		configs = new WifiConfigDef[aps.length];
		for (i=0; i<configs.length; i++)
			configs[i] = null;
	}

	public int getCount() {
		return aps.length;
	}

	public Object getItem(int position) {
		// restore the object
		if (null == configs[position]) {
			ObjectInputStream in = null;
			try {
				in = new ObjectInputStream(new FileInputStream(aps[position]));
				configs[position] = (WifiConfigDef)in.readObject();
				in.close();
			} catch (StreamCorruptedException e) {
				showError(context.getString(R.string.aps_corrupt));
				configs[position] = null;
			} catch (FileNotFoundException e) {
				showError(context.getString(R.string.aps_corrupt));
				configs[position] = null;
			} catch (IOException e) {
				showError(context.getString(R.string.aps_corrupt));
				configs[position] = null;
			} catch (ClassNotFoundException e) {
				showError(context.getString(R.string.aps_corrupt));
				configs[position] = null;
			}
		}
		return configs[position];
	}
	
	private void showError(String error)
	{
		Toast.makeText(context, error, Toast.LENGTH_SHORT);
	}

	public long getItemId(int position) {
		if (null == configs[position]) getItem(position);
		return (null == configs[position]) ? 0 : configs[position].getId();
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		return null;
	}
	
	// The view on how the line should be seen
}
